class Cat
# 實作內容
end
kitty = Cat.new('Mr Whiskers')
kitty.speak # 印出 Mr Whiskers meows.
nancy = Cat.new('Lamp')
nancy.speak # 印出 Lamp meows.
sherly = Cat.new('$$Money Bags$$')
sherly.speak # 印出 $$Money Bags$$ meows.
class Cat
def initialize(name)
@name = name
end
def speak
puts "#{@name} meows."
end
end
class Cat
def initialize(name)
@name = name
end
def speak
puts "#{@name} meows."
end
end
(剛好這題比較簡單,跟龍哥寫得一模一樣呢XD)
class Cat
# 等於同時寫
# attr_reader :name
# attr_writer :name
attr_accessor :name
def initialize(name)
@name = name
end
# (getter)這邊等於 attr_reader :name
# def name
# return @name
# end
# (getter)這邊等於 attr_writer :name
# def name=(new_name)
# @name = new_name
# end
end
kitty = Cat.new("yo")
kitty.name = "Mary"
puts kitty.name